package com.swjsj.hsk;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Component
public class IPCompared {

    private static Logger log = LoggerFactory.getLogger(IPCompared.class);

    @Value("${url_addr}")
    private String url_addr;
    @Value("${Authorization}")
    private String Authorization;

    public String ipComp() throws FileNotFoundException, IOException {
        String result = "";

        String remountipstr = getRemountIPByHSK();
        log.info("  获取路由器的ip：  " + remountipstr);

        if ("".equals(remountipstr)) {
            return "获取路由器IP地址出错";
        }

        String swjsjipstr = getIPByName(url_addr);

        log.info("  本地ping " + url_addr + "的ip：  " + swjsjipstr);

        if (null == swjsjipstr || "".equals(swjsjipstr.trim())) {
            swjsjipstr = "ping " + url_addr + "为空";
            sendGet(remountipstr);
            result = "   rountIP: " + remountipstr.trim();
            return url_addr + result;
        }
        if (remountipstr.indexOf(swjsjipstr.trim()) == -1) {
            sendGet(remountipstr);
            result = url_addr + "  rountIP: " + remountipstr.trim() + "and  " + url_addr + ":"
                    + swjsjipstr;
            return result;
        }
        return result;
    }

    public String sendGet(String ip) {
        String result = "";
        BufferedReader in = null;
        try {
            // String urlNameString = url + "?" + param;
            String url = "http://ddns.oray.com/ph/update?hostname=" + url_addr
                    + "&myip=" + ip;
            log.info(url);
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection
                    .setRequestProperty("Accept",
                            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Authorization",
                    Authorization);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            log.error(e.getMessage(), e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error(e2.getMessage(), e2);
            }
        }
        return result;
    }


    public static String getIPByName(String name) {
        InetAddress address = null;
        String ip = "";
        try {
            address = InetAddress.getByName(name);
            ip = address.getHostAddress().toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ip;
    }

    public static String getRemountIP() {
        Document doc = null;
        try {
            URL url = new URL("http://hereismyip.com/");
            doc = Jsoup.parse(url, 10 * 1000);
            Elements es = doc.select("table table");
            String ipstr = es.text();
            return ipstr.trim();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    public static String getRemountIPByHSK() {
        Document doc = null;
        try {
            URL url = new URL("http://ddns.oray.com/checkip");
            doc = Jsoup.parse(url, 10 * 1000);
            Elements es = doc.select("body");
            String ipstr = es.text();
            Pattern pattern = Pattern
                    .compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); // 正则表达式匹配格式
            Matcher matcher = pattern.matcher(ipstr);
            if (matcher.find()) {
                String srcStr = matcher.group(); // 这里得到的ip
                return srcStr;
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return getRemountIP();
        }
        return "";
    }


}
